package net.bingosoft.common.monitoring;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.ServletContextResource;

/**
 * 2008-4-15 下午07:27:15
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:代表服务器端资源的类,能够检查文件是否被修改
 * ChangeLog:
 */
public class ServletResource extends ServletContextResource{
	private static final Log log = LogFactory.getLog(ServletResource.class);
	private File resourceFile;
	private Long lastModified;
	private Map<File,Long> subFiles ;
	private boolean notExistInFileSystem = false;

	public ServletResource(ServletContext servletContext, String path) {
		super(servletContext, path);
		try {
			this.resourceFile = this.getFile();
			this.lastModified = this.resourceFile.lastModified();
			if(this.resourceFile.isDirectory()){
				File[] files = this.resourceFile.listFiles();
				this.subFiles = new HashMap<File, Long>(files.length);
				for(File f : files){
					subFiles.put(f, f.lastModified());
				}
			}
		} catch (IOException e) {
			notExistInFileSystem = true;
			log.warn("初始化可监控资源" + path + "时失败,如果您是以war包方式部署web应用则可忽略该错误.该错误发生的原因是：" + e.getMessage());
		}
	}
	/**
	 * 检查配置文件是否被修改了
	 * @return
	 */
	public boolean isChanged(){
		if(notExistInFileSystem || resourceFile == null || !resourceFile.exists()) return false;
		boolean isModified = false;
		if(this.lastModified < this.resourceFile.lastModified()){
			isModified = true;
			log.debug("Resource file ["+this.resourceFile.getAbsolutePath()+"] is Changed...");
		}else{
			for(File file : this.subFiles.keySet()){
				if(file.lastModified() > this.subFiles.get(file)){
					isModified = true;
					log.debug("Resource file ["+file.getAbsolutePath()+"] is Changed...");
					this.subFiles.put(file, file.lastModified());
					break;
				}
			}
		}
		return isModified;
	}


}
